public class Offer42 {

    public static void main(String[] args) {
        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};

        System.out.println(maxSubArray(nums));
    }

    public static int maxSubArrayDP(int[] nums) {
        int pre = 0, maxSum = nums[0];
        for (int num : nums) {
            pre = Math.max(pre + num, num);
            maxSum = Math.max(pre, maxSum);
        }
        return maxSum;
    }

    public static int maxSubArray(int[] nums) {
        return getInfo(nums, 0, nums.length - 1).mSum;
    }

    public static LeetCode53.Status getInfo(int[] a, int l, int r) {
        if (l == r) {
            return new LeetCode53.Status(a[l], a[l], a[l], a[l]);
        }

        int m = (l + r) >> 1;
        LeetCode53.Status lSub = getInfo(a, l, m);
        LeetCode53.Status rSub = getInfo(a, m + 1, r);
        return pushUp(lSub, rSub);
    }

    public static LeetCode53.Status pushUp(LeetCode53.Status l, LeetCode53.Status r) {
        int iSum = l.iSum + r.iSum;
        int lSum = Math.max(l.lSum, l.iSum + r.lSum);
        int rSum = Math.max(r.rSum, r.iSum + l.rSum);
        int mSum = Math.max(Math.max(l.mSum, r.mSum), l.rSum + r.lSum);
        return new LeetCode53.Status(lSum, rSum, mSum, iSum);
    }

    public static class Status {

        public int lSum, rSum, mSum, iSum;

        public Status(int lSum, int rSum, int mSum, int iSum) {
            this.lSum = lSum;
            this.rSum = rSum;
            this.mSum = mSum;
            this.iSum = iSum;
        }

    }

}
